package com.cheerscpl.protocol;

import com.cheerscpl.Constants;
import com.cheerscpl.protocol.model.DataPacket;
import com.cheerscpl.utils.PropertiesUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * Created by chenpuliang on 2017/6/4.
 */
public class DefaultParser {

    private static final Logger logger = LoggerFactory.getLogger(DefaultParser.class);

    public static final DataPacket parse(String source){
        if(StringUtils.isNotBlank(source)){
            DataPacket dataPacket = null;
            try {
                //eg. AA5 12345 1234512345 04F2B0
                String message = source.replaceFirst(Constants.PREFIX, "");
                String deviceId = message.substring(0, 5);
                String dateStr = message.substring(5, 15); //需实际做处理
                int length = Integer.valueOf(message.substring(15, 17)).intValue();
                String fid = message.substring(17, 19);
                String msgId = message.substring(19, 21);
                //默认不加密,机密级别等扩展可自行配置
                String encryt = PropertiesUtil.getInstance().get("default.encrypt");
                dataPacket = new DataPacket.DataPacketBuilder().devId(deviceId)
                        .length(length).date(new Date()).fid(fid).msgId(msgId).build();
            }catch (Exception e){ // 解析报错统一处理,不抛异常
                logger.error("parse err, exception is: {}", e.getMessage());
            }
            return dataPacket;
        }else {
            return null;
        }
    }
}
